import xlsx from 'xlsx'

/**
 * 读取文件
 * @param {File} file 文件
 */
export function readFile(file) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader()
    reader.onload = e => {
      const data = new Uint8Array(e.target.result)
      resolve(data)
    }
    reader.onerror = error => {
      reject(error)
    }
    reader.readAsArrayBuffer(file)
  })
}

/**
 * 从文件数据中读取某张表
 * @param {*} fileData 文件数据
 * @param {Number} index 表索引
 */
export function getTable(fileData, index = 0) {
  const workbook = xlsx.read(fileData, { type: 'array' })
  const firstWorksheet = workbook.Sheets[workbook.SheetNames[index]]
  const data = xlsx.utils.sheet_to_json(firstWorksheet, { header: 1 })
  return data
}
